package com.yz.xyt.componet;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yz.xyt.domain.Clazz;
import com.yz.xyt.domain.vo.ClazzImportVo;
import com.yz.xyt.service.IClazzService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * clazz监听器(EasyExcel导入)
 * @author JW.WANG
 */
@Component
public class ClazzListener extends AnalysisEventListener<ClazzImportVo> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClazzImportVo.class);

    private static final Integer COUNT = 50;

    private Set<ClazzImportVo> clazzSet = new HashSet<>();

    @Autowired
    private IClazzService clazzService;

    @Override
    public void invoke(ClazzImportVo clazz, AnalysisContext analysisContext) {
        LOGGER.info("解析了一条记录，" + clazz.toString());
        clazzSet.add(clazz);

        if(clazzSet.size() == COUNT){
            List<Clazz> clazzList = clazzService.convertClazz(clazzSet);
            if (!clazzList.isEmpty()){
                clazzService.syncAddClazz(clazzList);
            }
            clazzSet.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<Clazz> clazzList = clazzService.convertClazz(clazzSet);
        if (!clazzList.isEmpty()){
            clazzService.syncAddClazz(clazzList);
        }
        LOGGER.info("班级数据导入完成");
        clazzSet.clear();
    }
}
